package com.hunter.common.util;

import java.security.GeneralSecurityException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES算法
 * 128位的ecb模式
 * padding方式为 PKCS
 * */
public class AES32 {

	/**
	 * 加密
	 * @param pubKey 密钥
	 * @param content 明文
	 * @return
	 * */
	public static String aesEncrypt(String hexPubKey, String content) {
		// 处理密钥
        SecretKeySpec key = new SecretKeySpec(Hex.parseHexStr2Byte(hexPubKey), "AES");
        // 加密
        try {
			Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] encrypted = cipher.doFinal(content.getBytes());
 
			return Hex.parseByte2HexStr(encrypted).toLowerCase();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return null;
    }
	
	/**
	 * 解密
	 * @param pubKey 密钥 16进制字符串
	 * @param content 密文 16进制字符串
	 * @return
	 * */
	public static String aesDecrypt(String hexPubKey, String hexContent) {       
		byte[] rawKeyData=Hex.parseHexStr2Byte(hexPubKey);
		byte[] data=Hex.parseHexStr2Byte(hexContent); 
		// 处理密钥
        SecretKeySpec key = new SecretKeySpec(rawKeyData, "AES");
        // 解密
        Cipher cipher;
		try {
			cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
	        cipher.init(Cipher.DECRYPT_MODE, key);
	        return new String(cipher.doFinal(data));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (BadPaddingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
    }
   


	public static void main(String[] args) throws GeneralSecurityException {
		String a = aesEncrypt("41ce74b70c8c2b43253d74bf0cfcab43", "123456");
		String b = aesDecrypt("41ce74b70c8c2b4341ce74b70c8c2b43", "e88e6c09010441427110467574f0d81a");
		System.out.println(a);
		System.out.println(b);
	}
    
}
